﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;


namespace miniCCR
{
    public class ComDispatcher
    {
        public Dictionary<uint, GComponent> _ComList = new Dictionary<uint, GComponent>();
        public Queues.BlockingQueue<Operation> _Queues = new Queues.BlockingQueue<Operation>(1024);


        internal void Add(GComponent com)
        {
            lock (this)
            {
                _ComList.Add(com._Owner._ID, com);
            }
            
        }

        public bool Init()
        {
            ThreadPool.QueueUserWorkItem(WorkerThread);

            return true;
        }

        public void DequeueAll()
        {
            Operation op;

            while (_Queues.TryDequeue(out op))
            {

                if (op._ToID == 0)
                {

                    foreach (var com in _ComList.Values.ToArray())
                    {
                        com.Post(op);
                    }
                }
                else
                {
                    _ComList[op._ToID].Post(op);
                }
            }
            
        }

        public virtual void WorkerThread(object state)
        {
            //int i = (int)state;

            Operation op;

            while (true)
            {

                

                op = _Queues.Dequeue();

                if (op._ToID == 0)
                {
                    
                    List<GComponent> temp = new List<GComponent>();
                    temp.AddRange(  _ComList.Values.ToList());

                    foreach (var com in temp)
                    {
                        com.Post(op);
                    }
                }
                else
                {
                    _ComList[op._ToID].Post(op);
                }

                

                //_CMList[op._ID].OnMessage(op);
            }


        }



        public void Enqueue(Operation op)
        {
            _Queues.Enqueue(op);
        }
    }
}
